package com.example.controller;

import com.example.Product;
import com.example.server.IProductService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 产品测试入口
 *
 * @author sunhui
 */
@RestController
@RequestMapping("/prodcut")
public class ProductController {
    @Resource
    private IProductService iProductService;

    /**
     * 进行Eureka的发现服务
     */
    @Resource
    private DiscoveryClient client;

    /**
     * 根据id查询产品
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/get/{id}")
    @HystrixCommand(fallbackMethod = "getFallback")
    public Object get(@PathVariable("id") long id) {
        Product product = this.iProductService.get(id);
        if (product == null) {
            throw new RuntimeException("该产品已下架！");
        }
        return product;
    }

    /**
     * 熔断时候的回调方法
     *
     * @param id
     * @return
     */
    public Object getFallback(@PathVariable("id") long id) {
        Product product = new Product();
        product.setProductName("HystrixName");
        product.setProductDesc("HystrixDesc");
        product.setProductId(0L);
        return product;
    }

    /**
     * 添加产品
     *
     * @param product
     * @return
     */
    @RequestMapping(value = "/add")
    public Object add(@RequestBody Product product) {
        return this.iProductService.add(product);
    }

    /**
     * 查询所有产品
     *
     * @return
     */
    @RequestMapping(value = "/list")
    public Object list() {
        return this.iProductService.list();
    }

    /**
     * 返回发现服务信息
     *
     * @return
     */
    @RequestMapping("/discover")
    public Object discover() {
        // 直接返回发现服务信息
        return this.client;
    }
}
